import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Upload, message, Alert, List, Space, Progress, Row, Col, Button } from 'antd';
import { 
  CheckCircleOutlined, 
  CloseCircleOutlined,
  CloudUploadOutlined,
  RocketOutlined,
  ArrowRightOutlined,
} from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { uploadRecords, UploadResponse } from '@/api';

const { Dragger } = Upload;

const UploadPage = () => {
  const navigate = useNavigate();
  const [uploadResult, setUploadResult] = useState<UploadResponse | null>(null);
  const [uploading, setUploading] = useState(false);
  const [countdown, setCountdown] = useState(5);

  // 上传成功后的自动跳转
  useEffect(() => {
    if (uploadResult && uploadResult.success_count > 0) {
      // 显示成功提示和倒计时
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer);
            // 跳转到病历列表页面
            navigate('/records');
            return 0;
          }
          return prev - 1;
        });
      }, 1000);

      return () => clearInterval(timer);
    }
  }, [uploadResult, navigate]);

  // 手动跳转到病历列表
  const handleGoToRecords = () => {
    navigate('/records');
  };

  const uploadProps: UploadProps = {
    name: 'files',
    multiple: true,
    accept: '.json',
    showUploadList: true,
    customRequest: async ({ file, onSuccess, onError }) => {
      try {
        setUploading(true);
        const formData = new FormData();
        formData.append('files', file as File);
        
        const response = await uploadRecords([file as File]);
        const result = response.data.data;
        
        setUploadResult(result);
        setCountdown(5); // 重置倒计时
        
        if (result.success_count > 0) {
          message.success({
            content: `成功上传 ${result.success_count} 条病历，即将跳转到病历列表...`,
            duration: 4,
          });
          onSuccess?.(result);
        } else {
          message.error('上传失败，请检查文件格式');
          onError?.(new Error('上传失败'));
        }
      } catch (error) {
        console.error('上传错误:', error);
        message.error('上传失败，请重试');
        onError?.(error as Error);
      } finally {
        setUploading(false);
      }
    },
    onChange(info) {
      const { status } = info.file;
      if (status === 'uploading') {
        setUploadResult(null);
      }
    },
  };

  return (
    <div style={{ animation: 'fadeIn 0.6s ease-out' }}>
      <div style={{ marginBottom: 24 }}>
        <h1 className="page-title">病历上传</h1>
        <p className="page-subtitle">FILE UPLOAD</p>
      </div>

      {/* 使用说明 */}
      <Alert
        message="📋 使用说明"
        description={
          <div>
            <p style={{ marginBottom: 8 }}>
              <strong>第一步：</strong>上传病历文件（支持 JSON 格式，可批量上传）
            </p>
            <p style={{ marginBottom: 8 }}>
              <strong>第二步：</strong>上传成功后将自动跳转到病历列表
            </p>
            <p style={{ marginBottom: 0 }}>
              <strong>第三步：</strong>在病历列表中选择病历进行质量评估
            </p>
          </div>
        }
        type="info"
        showIcon
        style={{ 
          marginBottom: 32,
          borderRadius: 16,
          border: '1px solid #d9e8ff',
          background: 'linear-gradient(135deg, #f0f7ff 0%, #e6f4ff 100%)',
        }}
      />
      
      <div className="medical-card" style={{ padding: 60 }}>
        <Dragger 
          {...uploadProps} 
          disabled={uploading}
          style={{
            background: 'transparent',
            border: '2px dashed #C5CEE0',
            borderRadius: '24px',
            padding: '60px 40px',
            transition: 'all 0.3s ease',
          }}
        >
          <div style={{
            width: 100,
            height: 100,
            borderRadius: '50%',
            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            margin: '0 auto 24px',
            boxShadow: '0 12px 28px rgba(102, 126, 234, 0.3)',
          }}>
            <CloudUploadOutlined style={{ fontSize: 48, color: '#fff' }} />
          </div>
          <p style={{ 
            color: '#2E3A59', 
            fontSize: '20px',
            fontWeight: 300,
            marginBottom: 12,
            letterSpacing: '-0.3px',
          }}>
            点击或拖拽文件到此区域上传
          </p>
          <p style={{ 
            color: '#8F9BB3',
            fontSize: 14,
            margin: '0 0 16px 0',
          }}>
            支持单个或批量上传病历文件 • 仅支持 JSON 格式 • 自动解析病历数据
          </p>
          <div style={{
            display: 'inline-flex',
            alignItems: 'center',
            gap: 8,
            padding: '8px 20px',
            background: 'rgba(102, 126, 234, 0.1)',
            borderRadius: 20,
            fontSize: 13,
            color: '#667eea',
            fontWeight: 500,
          }}>
            <RocketOutlined />
            <span>上传成功后自动跳转到病历列表</span>
          </div>
        </Dragger>
      </div>

      {uploadResult && (
        <div style={{ marginTop: 48 }}>
          {/* 成功提示和跳转倒计时 */}
          {uploadResult.success_count > 0 && (
            <Alert
              message={
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <span>
                    <CheckCircleOutlined style={{ marginRight: 8 }} />
                    上传成功！{countdown > 0 ? `${countdown} 秒后自动跳转到病历列表...` : '正在跳转...'}
                  </span>
                  <Button
                    type="primary"
                    icon={<ArrowRightOutlined />}
                    onClick={handleGoToRecords}
                    style={{
                      borderRadius: 8,
                      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                      border: 'none',
                    }}
                  >
                    立即前往评估
                  </Button>
                </div>
              }
              type="success"
              showIcon={false}
              style={{
                marginBottom: 32,
                borderRadius: 16,
                border: '1px solid #b7eb8f',
                background: 'linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%)',
              }}
            />
          )}

          <div style={{ marginBottom: 32 }}>
            <h2 style={{ 
              fontSize: '24px', 
              fontWeight: 300,
              color: '#2E3A59',
              marginBottom: 8,
              letterSpacing: '-0.5px',
            }}>
              上传结果
            </h2>
            <p className="page-subtitle">UPLOAD RESULT</p>
          </div>
          
          <Row gutter={[32, 32]}>
            <Col xs={24} md={12}>
              <div className="stat-card-circle">
                <div style={{ display: 'flex', alignItems: 'center', gap: 24 }}>
                  <div style={{
                    width: 80,
                    height: 80,
                    borderRadius: '50%',
                    background: 'linear-gradient(135deg, #50E3C2 0%, #00D68F 100%)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    boxShadow: '0 8px 20px rgba(80, 227, 194, 0.3)',
                    flexShrink: 0,
                  }}>
                    <CheckCircleOutlined style={{ fontSize: 32, color: '#fff' }} />
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, color: '#8F9BB3', marginBottom: 8, fontWeight: 500 }}>成功上传</div>
                    <div style={{ fontSize: 36, fontWeight: 300, color: '#2E3A59' }}>
                      {uploadResult.success_count} <span style={{ fontSize: 16, color: '#8F9BB3' }}>条</span>
                    </div>
                    <Progress 
                      percent={100} 
                      strokeColor={{
                        '0%': '#50E3C2',
                        '100%': '#00D68F',
                      }}
                      showInfo={false}
                      strokeWidth={6}
                      style={{ marginTop: 12 }}
                    />
                  </div>
                </div>
              </div>
            </Col>
            <Col xs={24} md={12}>
              <div className="stat-card-circle">
                <div style={{ display: 'flex', alignItems: 'center', gap: 24 }}>
                  <div style={{
                    width: 80,
                    height: 80,
                    borderRadius: '50%',
                    background: 'linear-gradient(135deg, #FF6B9D 0%, #FF3D71 100%)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    boxShadow: '0 8px 20px rgba(255, 107, 157, 0.3)',
                    flexShrink: 0,
                  }}>
                    <CloseCircleOutlined style={{ fontSize: 32, color: '#fff' }} />
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, color: '#8F9BB3', marginBottom: 8, fontWeight: 500 }}>上传失败</div>
                    <div style={{ fontSize: 36, fontWeight: 300, color: '#2E3A59' }}>
                      {uploadResult.failed_count} <span style={{ fontSize: 16, color: '#8F9BB3' }}>条</span>
                    </div>
                    <Progress 
                      percent={uploadResult.failed_count > 0 ? 100 : 0}
                      strokeColor={{
                        '0%': '#FF6B9D',
                        '100%': '#FF3D71',
                      }}
                      showInfo={false}
                      strokeWidth={6}
                      style={{ marginTop: 12 }}
                    />
                  </div>
                </div>
              </div>
            </Col>
          </Row>

            {uploadResult.records.length > 0 && (
              <div style={{ marginTop: 48 }}>
                <h3 style={{ 
                  fontSize: '18px', 
                  fontWeight: 400,
                  color: '#2E3A59',
                  marginBottom: 20,
                }}>
                  成功上传的病历
                </h3>
                <div className="medical-card" style={{ padding: 0, overflow: 'hidden' }}>
                  <List
                    dataSource={uploadResult.records}
                    renderItem={(record, index) => (
                      <List.Item style={{ 
                        padding: '20px 32px',
                        borderBottom: index < uploadResult.records.length - 1 ? '1px solid rgba(0,0,0,0.06)' : 'none',
                        transition: 'all 0.3s',
                        background: 'transparent',
                      }}>
                        <Space align="center">
                          <div style={{
                            width: 40,
                            height: 40,
                            borderRadius: '50%',
                            background: 'linear-gradient(135deg, #50E3C2 0%, #00D68F 100%)',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                          }}>
                            <CheckCircleOutlined style={{ color: '#fff', fontSize: 18 }} />
                          </div>
                          <div>
                            <div style={{ fontSize: 15, fontWeight: 500, color: '#2E3A59' }}>
                              {record.patient_name}
                            </div>
                            <div style={{ fontSize: 13, color: '#8F9BB3' }}>
                              {record.department || '未知科室'}
                            </div>
                          </div>
                        </Space>
                      </List.Item>
                    )}
                  />
                </div>
              </div>
            )}

            {uploadResult.errors.length > 0 && (
              <div style={{ marginTop: 48 }}>
                <h3 style={{ 
                  fontSize: '18px', 
                  fontWeight: 400,
                  color: '#2E3A59',
                  marginBottom: 20,
                }}>
                  失败记录
                </h3>
                <div className="medical-card" style={{ padding: 0, overflow: 'hidden' }}>
                  <List
                    dataSource={uploadResult.errors}
                    renderItem={(error, index) => (
                      <List.Item style={{ 
                        padding: '24px 32px',
                        borderBottom: index < uploadResult.errors.length - 1 ? '1px solid rgba(0,0,0,0.06)' : 'none',
                        background: 'transparent',
                      }}>
                        <Space direction="vertical" style={{ width: '100%' }} size="middle">
                          <Space>
                            <div style={{
                              width: 40,
                              height: 40,
                              borderRadius: '50%',
                              background: 'linear-gradient(135deg, #FF6B9D 0%, #FF3D71 100%)',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                            }}>
                              <CloseCircleOutlined style={{ color: '#fff', fontSize: 18 }} />
                            </div>
                            <div>
                              <div style={{ fontSize: 15, fontWeight: 500, color: '#2E3A59' }}>
                                {error.filename}
                              </div>
                              <div style={{ fontSize: 13, color: '#FF3D71', marginTop: 4 }}>
                                {error.error}
                              </div>
                            </div>
                          </Space>
                        </Space>
                      </List.Item>
                    )}
                  />
                </div>
              </div>
            )}
        </div>
      )}
    </div>
  );
};

export default UploadPage;

